package com.example.dw.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.dw.entity.Exam;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 考试Mapper接口
 * @author system
 * @since 2024-01-01
 */
@Mapper
public interface ExamMapper extends BaseMapper<Exam> {

    /**
     * 根据考试ID获取考试详情
     */
    @Select("SELECT * FROM exams WHERE exam_id = #{examId}")
    Exam getExamById(@Param("examId") Integer examId);

    /**
     * 根据课程类型ID获取考试列表
     */
    @Select("SELECT e.* FROM exams e " +
            "INNER JOIN questionbank q ON FIND_IN_SET(q.question_id, e.question_ids) " +
            "WHERE q.courseTypeid = #{courseTypeid} " +
            "GROUP BY e.exam_id ORDER BY e.created_at DESC")
    List<Exam> getExamsByCourseType(@Param("courseTypeid") Integer courseTypeid);

    /**
     * 根据课程类型ID分页获取考试列表
     */
    @Select("SELECT e.* FROM exams e " +
            "INNER JOIN questionbank q ON FIND_IN_SET(q.question_id, e.question_ids) " +
            "WHERE q.courseTypeid = #{courseTypeid} " +
            "GROUP BY e.exam_id ORDER BY e.created_at DESC " +
            "LIMIT #{offset}, #{size}")
    List<Exam> getExamsByCourseTypePage(@Param("courseTypeid") Integer courseTypeid,
                                        @Param("offset") Integer offset,
                                        @Param("size") Integer size);

    /**
     * 根据课程类型ID获取考试总数
     */
    @Select("SELECT COUNT(DISTINCT e.exam_id) FROM exams e " +
            "INNER JOIN questionbank q ON FIND_IN_SET(q.question_id, e.question_ids) " +
            "WHERE q.courseTypeid = #{courseTypeid}")
    Integer getExamCountByCourseType(@Param("courseTypeid") Integer courseTypeid);

    /**
     * 获取用户创建的所有考试
     */
    @Select("SELECT * FROM exams WHERE created_by = #{userid} ORDER BY created_at DESC")
    List<Exam> getAllExamsByUser(@Param("userid") Integer userid);

    /**
     * 根据创建者分页获取考试
     */
    @Select("SELECT * FROM exams WHERE created_by = #{userid} " +
            "ORDER BY created_at DESC LIMIT #{offset}, #{size}")
    List<Exam> getExamsByUserPage(@Param("userid") Integer userid,
                                  @Param("offset") Integer offset,
                                  @Param("size") Integer size);

    /**
     * 获取用户创建的考试总数
     */
    @Select("SELECT COUNT(*) FROM exams WHERE created_by = #{userid}")
    Integer getExamCountByUser(@Param("userid") Integer userid);

    /**
     * 根据考试名称模糊搜索
     */
    @Select("SELECT * FROM exams WHERE exam_name LIKE CONCAT('%', #{examName}, '%') " +
            "ORDER BY created_at DESC LIMIT #{offset}, #{size}")
    List<Exam> searchExamsByName(@Param("examName") String examName,
                                 @Param("offset") Integer offset,
                                 @Param("size") Integer size);
} 